package com.qf.springmvc2.controller;

import com.qf.springmvc2.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Controller
@SessionAttributes({"user"})
public class LoginController {

    // @PostMapping 这个注解的意思是只能接收post请求
    @PostMapping("/login")
    public String login(User user, Model model, String code, HttpServletRequest request){
        // 先获取session中存的验证码 跟用户传入的验证码进行比较 如果不一致 直接返回验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (Objects.equals(captcha, code)) {
            if (Objects.equals(user.getName(), "admin") && Objects.equals(user.getPassword(), "123456")) {
                // 登录成功
                model.addAttribute("user", user);
                return "welcome";
            } else {
                model.addAttribute("error", "用户名或密码错误");
            }
        } else {
            // 验证码输入错误
            model.addAttribute("error", "验证码错误");
        }
        return "index";
    }

}
